package com.ruyiadmin.springcloud.producer.common.utils.core;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import com.ruyiadmin.springcloud.producer.common.beans.system.SM2Config;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * SM2加解密工具类
 *
 * @author RuYiAdmin
 * @since 2022-10-09
 */
@Component
public class RuYiSM2Util {
    @Resource
    private SM2Config sm2Config;
    public static RuYiSM2Util sm2Util;

    @PostConstruct
    public void init() {
        sm2Util = this;
        sm2Util.sm2Config = this.sm2Config;
    }

    /**
     * 公钥加密
     *
     * @param plainText 明文
     * @return 密文
     */
    public static String encrypt(String plainText) {
        SM2 sm2 = SmUtil.sm2(sm2Util.sm2Config.getPrivateKey(), sm2Util.sm2Config.getPublicKey());
        return sm2.encryptBcd(plainText, KeyType.PublicKey);
    }

    /**
     * 私钥解密
     *
     * @param cipherText 密文
     * @return 明文
     */
    public static String decrypt(String cipherText) {
        SM2 sm2 = SmUtil.sm2(sm2Util.sm2Config.getPrivateKey(), sm2Util.sm2Config.getPublicKey());
        return StrUtil.utf8Str(sm2.decryptFromBcd(cipherText, KeyType.PrivateKey));
    }
}
